<template>
  <div class="table-box">
    <ProTable ref="proTable" title="部门列表" :indent="20" :pagination="false" :columns="columns" :request-api="getTableTree">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'sys:sys_dept:save'" type="primary" :icon="CirclePlus" @click="onSave({})">新增部门</el-button>
      </template>
      <!-- 菜单操作 -->
      <template #operation="scope">
        <el-button v-auth="'sys:sys_dept:update'" type="primary" link :icon="EditPen" @click="onUpdate(scope.row)">
          编辑
        </el-button>
        <el-button
          v-auth="'sys:sys_dept:save'"
          v-if="scope.row.deptType != 3"
          type="primary"
          link
          :icon="EditPen"
          @click="onSave(scope.row)"
        >
          新增
        </el-button>
        <el-button v-auth="'sys:sys_dept:delete'" type="danger" link :icon="Delete" @click="onDelete(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <DeptOperateDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="departmentManage">
import { ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { deleteSysDept, getSysDeptTree, saveSysDept, SysDeptInfoResult, updateSysDept } from "@/api/modules/sys/dept";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import DeptOperateDrawer from "@/views/system/departmentManage/DeptOperateDrawer.vue";
import { useHandleData } from "@/hooks/useHandleData";

const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps[] = [
  { prop: "deptName", label: "部门名称", width: 200, align: "left", fixed: "left" },
  { prop: "remark", label: "描述" },
  { prop: "updateTime", label: "最后更新时间" },
  { prop: "operation", label: "操作", width: 250, fixed: "right" }
];

const getTableTree = () => {
  return getSysDeptTree();
};

const drawerRef = ref<InstanceType<typeof DeptOperateDrawer> | null>(null);

const onSave = (row: Partial<SysDeptInfoResult> = {}) => {
  drawerRef.value?.openDrawer({
    title: "新增",
    isSave: true,
    isUpdate: false,
    row: { ...row },
    api: saveSysDept,
    getTableList: proTable.value?.getTableList
  });
};

const onUpdate = (row: Partial<SysDeptInfoResult> = {}) => {
  drawerRef.value?.openDrawer({
    title: "更新",
    isSave: false,
    isUpdate: true,
    row: { ...row },
    api: updateSysDept,
    getTableList: proTable.value?.getTableList
  });
};

// 删除信息
const onDelete = async (row: SysDeptInfoResult) => {
  await useHandleData(deleteSysDept, row.id, `删除【${row.deptName}】`);
  proTable.value?.getTableList();
};
</script>
